package com.hopeland.androidpc.jilintongdaomen;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hopeland.androidpc.jilintongdaomen.network.AddDataBean;
import com.hopeland.androidpc.jilintongdaomen.network.KillerApi;
import com.hopeland.androidpc.jilintongdaomen.network.MainApi;
import com.hopeland.androidpc.jilintongdaomen.network.MyObserve;
import com.hopeland.androidpc.jilintongdaomen.network.QueryRfidBean;
import com.hopeland.androidpc.jilintongdaomen.room.RfidDataBase;
import com.hopeland.androidpc.jilintongdaomen.room.entry.RfidRoomInfo;
import com.hopeland.androidpc.jilintongdaomen.uhf.ConfigActivity;
import com.hopeland.androidpc.jilintongdaomen.uhf.UHFBaseActivity;
import com.hopeland.androidpc.jilintongdaomen.uhf.UHFMain;
import com.rfidread.Helper.Helper_ThreadPool;
import com.rfidread.Interface.IAsynchronousMessage;
import com.rfidread.Models.GPI_Model;
import com.rfidread.Models.Tag_Model;
import com.rfidread.RFIDReader;
import com.rfidread.usbserial.driver.UsbSerialPort;
import com.util.AddRfidsBean;
import com.util.AddressEvent;
import com.util.LogUtils;
import com.util.PreferenceUtils;
import com.util.RecyclerViewUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Completable;
import io.reactivex.MaybeObserver;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class MainDataActivity extends UHFBaseActivity implements
        IAsynchronousMessage  {

    private RfidDataBase myAppDataBase;

    RecyclerView mRecyclerView;

    private  AddListHkAdapter mCheckListAdapter;
    private TextView tv_struct_gwm,tv_struct_cpm,btn_struct_read,btn_struct_up,btn_struct_down,btn_set;

    private HashMap<String, Tag_Model> hmList = new HashMap<String, Tag_Model>();
    private Object hmList_Lock = new Object();
    private Boolean IsFlushList = true; // 是否刷列表
    private Object beep_Lock = new Object();
    ToneGenerator toneGenerator = new ToneGenerator(AudioManager.STREAM_SYSTEM,
            ToneGenerator.MAX_VOLUME);

    private int readTime = 0;
    private int lastReadCount = 0;
    private int totalReadCount = 0; // 总读取次数

    private List<AddRfidsBean> addRfidsBeanList = new ArrayList<>();

    public static String http_url = "";
    public static String devices_address = "";
    public static String defaut_url = "http://192.168.20.48:8088/";
    public static String defaut_address =  "/dev/ttyS7:115200";


    private boolean up_state = false;
    private boolean down_state = false;

    private int up_down_index = 0;//上线 或者下线的状态  0是初始状态  1是上线先触发   2是下线先触发

    //2号区域  "S2BDOOR3-1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 创建
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.item_main_data);
        EventBus.getDefault().register(this);
        http_url = PreferenceUtils.getData(App.application,PreferenceUtils.http_url);
        if (TextUtils.isEmpty(http_url)){
            PreferenceUtils.setData(App.application,PreferenceUtils.http_url,defaut_url);
            http_url = defaut_url;
        }
        devices_address = PreferenceUtils.getData(App.application,PreferenceUtils.device_address);
        if (TextUtils.isEmpty(devices_address)){
            PreferenceUtils.setData(App.application,PreferenceUtils.device_address,defaut_address);
            devices_address = defaut_address;
        }

        if (myAppDataBase == null) {
            myAppDataBase =  RfidDataBase.getInstance(this);
        }

        mRecyclerView = findViewById(R.id.mRecyclerView);
        tv_struct_gwm =  findViewById(R.id.tv_struct_gwm);
        tv_struct_cpm =  findViewById(R.id.tv_struct_cpm);
        btn_struct_read = findViewById(R.id.btn_struct_read);
        btn_struct_up = findViewById(R.id.btn_struct_up);
        btn_struct_down = findViewById(R.id.btn_struct_down);

        btn_set = findViewById(R.id.btn_set);
        tv_struct_cpm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onLogin();
                //startActivity(new Intent(MainDataActivity.this,SettingActivity.class));
            }
        });
        btn_set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainDataActivity.this,SettingActivity.class));
            }
        });

//        RfidRoomInfo rfidRoomInfo = new RfidRoomInfo("5341434330303335302D533242465044","S2BDOOR3-1","1","S2BFPD01","2019.10.25");
//        Completable completable = myAppDataBase.RfidRoomDao().insert(rfidRoomInfo);
//        new CompositeDisposable().add(completable.subscribeOn(Schedulers.io())
//                .observeOn(Schedulers.io()).subscribe());//保存数据到room数据库

        InitRecyclerView();
        getData();


    }

    private void InitRecyclerView() {
        mCheckListAdapter = new AddListHkAdapter();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        RecyclerViewUtil.setDefaultDivider(mRecyclerView, linearLayoutManager);
        mRecyclerView.setAdapter(mCheckListAdapter);


    }

    private void getData(){
        myAppDataBase.RfidRoomDao().queryAll()
                .subscribeOn(Schedulers.io()).observeOn(Schedulers.io())
                .subscribe(new MaybeObserver<List<RfidRoomInfo>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onSuccess(List<RfidRoomInfo> tempRoomInfo) {
                        if (tempRoomInfo != null) {
                            LogUtils.e("queryWeatherTemp onError" + tempRoomInfo.toString());
                            for (int i = 0;i < tempRoomInfo.size();i++){
                                RfidRoomInfo rfidRoomInfo = tempRoomInfo.get(i);
                                AddRfidsBean rfidsBean = new AddRfidsBean(i,rfidRoomInfo.workstation,rfidRoomInfo.prodtype,rfidRoomInfo.flights,rfidRoomInfo.up_time);
                                addRfidsBeanList.add(rfidsBean);
                            }
                            mCheckListAdapter.setNewData(addRfidsBeanList);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.e("queryWeatherTemp onError");
                    }

                    @Override
                    public void onComplete() {
                        LogUtils.e("queryWeatherTemp onComplete");

                    }
                });
    }

    private void getCustomerList(String epc) {
        String tagdata = PreferenceUtils.HexToASCII(epc);
        AddDataBean addDataBean = new AddDataBean();
        addDataBean.tagdata = tagdata;
        addDataBean.tagtype = "cp";
        addDataBean.routtype = "1";


        MainApi.getInstance().getApi( KillerApi.class)
                .addRfidDataIn(addDataBean)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new MyObserve<QueryRfidBean>() {
                    @Override
                    public void onNetError(Throwable e) {
                        String vStr = "网络接口报错";
                        sendMessage(MSG_SHOW_TIP, vStr);
                        up_down_index = 0;
                    }

                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(QueryRfidBean customerBean) {
                        up_down_index = 0;
                        if (customerBean != null && customerBean.getCode() == 200) {
                            if (customerBean.getData() != null && TextUtils.isEmpty(customerBean.getData().getTagdata())) {
                                btn_struct_up.setSelected(true);
                                RfidRoomInfo rfidRoomInfo = new RfidRoomInfo(epc,tagdata, customerBean.getData().getWorkstation(), customerBean.getData().getProdtype(),
                                        customerBean.getData().getFlights(), customerBean.getData().getDt());
                                Completable completable = myAppDataBase.RfidRoomDao().insert(rfidRoomInfo);
                                new CompositeDisposable().add(completable.subscribeOn(Schedulers.io())
                                        .observeOn(Schedulers.io()).subscribe());//保存数据到room数据库

                                Observable.timer(1, TimeUnit.SECONDS)
                                        .observeOn(Schedulers.io())
                                        .subscribe(new Consumer<Long>() {
                                            @Override
                                            public void accept(Long aLong) throws Exception {
                                                getData();
                                            }
                                        });

                                Observable.timer(3, TimeUnit.SECONDS)
                                        .observeOn(Schedulers.io())
                                        .subscribe(new Consumer<Long>() {
                                            @Override
                                            public void accept(Long aLong) throws Exception {
                                                btn_struct_up.setSelected(false);
                                            }
                                        });
                            }


                            if (customerBean.getData() != null && !TextUtils.isEmpty(customerBean.getData().getTagdata())) {
                                btn_struct_down.setSelected(true);
                                getrfidquery(customerBean.getData().getTagdata());
                                Observable.timer(1, TimeUnit.SECONDS)
                                        .observeOn(Schedulers.io())
                                        .subscribe(new Consumer<Long>() {
                                            @Override
                                            public void accept(Long aLong) throws Exception {

                                            }
                                        });

                                Observable.timer(3, TimeUnit.SECONDS)
                                        .observeOn(Schedulers.io())
                                        .subscribe(new Consumer<Long>() {
                                            @Override
                                            public void accept(Long aLong) throws Exception {
                                                btn_struct_down.setSelected(false);
                                            }
                                        });
                            }
                        }

                        if (customerBean != null && customerBean.getCode() == 200) {
                            String vStr = "重复提交";
                            sendMessage(MSG_SHOW_TIP, vStr);
                        }
                    }
                });
    }

    private void getrfidquery(String epc_asicc){
        myAppDataBase.RfidRoomDao().queryRfidData(epc_asicc)
                .subscribeOn(Schedulers.io()).observeOn(Schedulers.io())
                .subscribe(new MaybeObserver<RfidRoomInfo>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onSuccess(RfidRoomInfo tempRoomInfo) {
                        if (tempRoomInfo != null) {
                            Completable completable = myAppDataBase.RfidRoomDao().delete(tempRoomInfo);
                            new CompositeDisposable().add(completable.subscribeOn(Schedulers.io())
                                    .observeOn(Schedulers.io()).subscribe());//保存数据到room数据库
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.e("queryWeatherTemp onError");
                    }

                    @Override
                    public void onComplete() {
                        LogUtils.e("queryWeatherTemp onComplete");

                    }
                });
    }
    @Override
    protected void onDestroy() {
        // 释放
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        // 待机锁屏
        super.onPause();
    }

    @Override
    protected void onResume() {
        // 待机恢复
        super.onResume();
        onLogin();
    }
    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    public void Event(AddressEvent event) {
        LogUtils.e("AddressEvent");
    }


    //连接对话框
    protected void onLogin()
    {
        String  connparam = devices_address;
        sendMessage(MSG_SHOW_WAIT,
                getString(R.string.str_please_waitting));
        String vStr = "Note:";
        boolean isConnectOK = false;
        if(InitConnect(connparam)) //连接读写器
        {
            vStr = getString(R.string.str_LoginSuccess);
            isConnectOK = true;
        }
        else{
            vStr = getString(R.string.str_LoginFaild);
        }
        sendMessage(MSG_SHOW_TIP, vStr);
        sendMessage(MSG_HIDE_WAIT, null);
        //
        if(isConnectOK) {

//            Intent intentA = new Intent();
//            intentA.setClass(ItemMainActivity.this, (Class<?>) map.get("itemActivity"));
//            startActivity(intentA);
            LogUtils.e("onLogin=");
            Init();
        }


    }

    //初始化
    protected boolean InitConnect(String connparam)
    {
        boolean ret=false;

        if(Rfid_RS232_Init(connparam,this))
        {
            ret=true;
        }
        return ret;
    }

    //初始化
    protected void Init() {
        try {
            Thread.sleep(20);
            try {
                RFIDReader._Config.Stop(ConnID);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Thread.sleep(20);
            super.UHF_SetTagUpdateParam(); // 设置标签重复上传时间为20ms
        } catch (Exception ee) {
        }


        Refush();
        //
        RFIDReader.setAsynchronousMessage(ConnID, this);
        LogUtils.e("setAsynchronousMessage=");
    }

    //刷新显示线程
    protected void Refush()
    {
        IsFlushList = true;
        Helper_ThreadPool.ThreadPool_StartSingle(new Runnable() { // 蜂鸣器发声
            @Override
            public void run() {
                while (IsFlushList) {
                    synchronized (beep_Lock) {
                        try {
                            beep_Lock.wait();
                        } catch (InterruptedException e) {
                        }
                    }
                    if (IsFlushList) {
                        toneGenerator
                                .startTone(ToneGenerator.TONE_PROP_BEEP);
                    }

                }
            }
        });
    }
    // 获得更新数据源
    @SuppressWarnings({ "rawtypes", "unused" })
    protected List<String> GetData() {
        List<String> rt = new ArrayList();
        synchronized (hmList_Lock) {
            // if(hmList.size() > 0){ //
            Iterator iter = hmList.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                String key = (String) entry.getKey();
                Tag_Model val = (Tag_Model) entry.getValue();
                rt.add(val._EPC);

            }
            // }
        }
        return rt;
    }

    @Override
    public void WriteDebugMsg(String s, String s1) {

    }

    @Override
    public void WriteLog(String s, String s1) {

    }

    @Override
    public void PortConnecting(String s) {

    }

    @Override
    public void PortClosing(String s) {
        LogUtils.e("PortClosing=");
    }

    @Override
    public void OutPutTags(Tag_Model model) {
        try {
            synchronized (hmList_Lock) {
                if (hmList.containsKey(model._EPC + model._TID)) {
                    Tag_Model tModel = hmList.get(model._EPC + model._TID);
                    tModel._TotalCount++;
                    model._TotalCount = tModel._TotalCount;
                    hmList.remove(model._EPC + model._TID);
                    hmList.put(model._EPC + model._TID, model);
                } else {
                    model._TotalCount = 1;
                    hmList.put(model._EPC + model._TID, model);
                }
            }
            synchronized (beep_Lock) {
                beep_Lock.notify();
            }
            totalReadCount++;
            LogUtils.e("totalReadCount="+totalReadCount);
        } catch (Exception ex) {
            Log.d("Debug", "Tags output exceptions:" + ex.getMessage());
        }
    }

    @Override
    public void OutPutTagsOver(String s) {
        LogUtils.e("OutPutTagsOver=");
        btn_struct_read.setSelected(false);

        List<String> list = GetData();
        if (list != null && list.size() > 0){
            tv_struct_cpm.setText(list.get(0));
        }
    }

    private boolean readProcess = false;//一个读取过程
    @Override
    public void GPIControlMsg(String s, GPI_Model gpi_model) {
        LogUtils.e("GPIControlMsg=");
        btn_struct_read.setSelected(true);
        tv_struct_cpm.setText("");
        LogUtils.e("gpi_model.GpiIndex="+gpi_model.GpiIndex+" gpi_model.GpiState="+gpi_model.GpiState+" gpi_model.StartOrStop="+gpi_model.StartOrStop);

        if (up_down_index == 0){
            if (gpi_model.GpiIndex == 1 && gpi_model.GpiState == 1){//1号gpio触发，状态是开始读取
                up_down_index =1;
                readProcess = true;
                delaytime();
                String vStr = "1号gpio触发读取";
                sendMessage(MSG_SHOW_TIP, vStr);
            }
        }

        if (up_down_index == 1 && readProcess){
            if (gpi_model.GpiIndex == 1 && gpi_model.GpiState == 0){//1号gpio触发，状态是读取结束
                up_down_index = 3;
                readProcess = false;
                String string =  tv_struct_cpm.getText().toString();
                getCustomerList(string);
                String vStr = "1号gpio读取结束";
                sendMessage(MSG_SHOW_TIP, vStr);
            }
        }

        //////////////////////////////////////////////////////////////////////////////
        //下面是下线逻辑

//        if (up_down_index == 0){
//            if (gpi_model.GpiIndex == 2 && gpi_model.GpiState == 1){//2号gpio触发，状态是开始读取
//                up_down_index = 2;
//                readProcess = true;
//                delaytime();
//                String vStr = "2号gpio触发";
//                sendMessage(MSG_SHOW_TIP, vStr);
//            }
//        }
//
//        if (up_down_index == 2 && readProcess){
//            if (gpi_model.GpiIndex == 1 && gpi_model.GpiState == 0){//1号gpio触发，状态是读取结束
//                up_down_index = 3;
//                readProcess = false;
//                String vStr = "1号gpio触发";
//                sendMessage(MSG_SHOW_TIP, vStr);
//                String string =  tv_struct_cpm.getText().toString();
//               // getCustomerList(string);
//            }
//        }
    }

    private void delaytime(){
        Observable.timer(5, TimeUnit.SECONDS)
                .observeOn(Schedulers.io())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        readProcess = false;
                        up_down_index = 0;
                    }
                });
    }

    @Override
    public void OutPutScanData(String s, byte[] bytes) {
        LogUtils.e("OutPutScanData=");
    }
}
